<template>
  <div class="home page">
    <!-- 顶部标题 -->
    <div class="header">
      <span>安泰校友会</span>
    </div>

    <!-- 学校logo和背景 -->
    <div class="school-header">
      <div class="logo-container">
        <img class="school-logo" src="@/assets/img/dut_logo.png" alt="安泰校友会"/>
        <span class="school-name">安泰XX大学校友会</span>
      </div>
    </div>

    <!-- 轮播图 -->
    <swiper
      :show-desc-mask="false"
      loop
      auto
      :interval="4000"
      @on-index-change="onIndexChange"
      :show-dots="true"
      class="swiper_box"
    >
      <swiper-item>
        <img src="@/assets/img/banner1.png" alt="banner1"/>
      </swiper-item>
      <swiper-item>
        <img src="@/assets/img/banner2.png" alt="banner2"/>
      </swiper-item>
    </swiper>

    <!--功能入口 -->
    <div class="quick_entry">
      <div class="entry_item" @click="goActivity">
        <img src="@/assets/img/building_icon.png" alt=""/>
        <span>活动</span>
      </div>
      <div class="entry_item" @click="goMutual">
        <img src="@/assets/img/mutual.png" alt=""/>
        <span>合作</span>
      </div>
    </div>

    <!-- 新闻区域 -->
    <div class="news_section">
      <div class="news_header">
        <div class="news_title">
          <div class="title_bar"></div>
          <span>新闻</span>
        </div>
      </div>
      <div class="news-list">
        <div 
          v-for="item in newsList" 
          :key="item.id" 
          class="news-item"
          @click="handleNewsClick(item)"
        >
          <!-- 根据type显示不同的图标 -->
          <div class="news-icon">
            <img 
              :src="getNewsIcon(item.type)" 
              :alt="getNewsTypeText(item.type)"
              class="type-icon"
            >
          </div>
          <div class="news-content">
            <div class="news-title">{{ item.title }}</div>
            <div class="news-info">
              <span class="news-type">{{ getNewsTypeText(item.type) }}</span>
              <span class="news-time">{{ formatDate(item.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
import {
  Tab,
  TabItem,
  GridItem,
  Grid,
  Flexbox,
  FlexboxItem,
  Swiper,
  SwiperItem,
  Popup
} from "vux";
import {
  getToken,
  setToken,
  getWxUserinfoCookies,
  setWxUserinfoCookies,
  removeToken,
  removeWxUserinfoCookies
} from "@/api/auth";
import {
  getWxOpenId,
  getWxUserInfo,
  getPatientList,
  getWxSign,
  getBannerList,
  getNoticeList,
  loginByOpenId,
  getLoginUserInfo,
  getNewsList,
  getUnreadMessageCount
} from "@/api/api";
import Vue from "vue";

export default {
  name: "home",
  components: {
    Popup,
    Tab,
    TabItem,
    Flexbox,
    FlexboxItem,
    Swiper,
    SwiperItem
  },
  data() {
    return {
      alertShow: false,
      popup: 0,
      index: 0,
      isbind: false,
      isLogin: false,
      noticeList: [],
      articleList: [],
      homeList: [],
      firstHomeList: [],
      bannerIndex: 0,
      selectIndex: 2,
      searchInput: "",
      errorImg01: 'this.src="' + require("@/assets/img/img_male.png") + '"',
      errorImg02: 'this.src="' + require("@/assets/img/icon_female.png") + '"',
      newsList: [],
      defaultNewsImg: 'this.src="' + require("@/assets/img/news_default.png") + "''",
      unreadCount: 0
    };
  },
  created() {
    if (window.localStorage.getItem("sheetIndex")) {
      this.selectIndex = parseInt(window.localStorage.getItem("sheetIndex"));
    }
    this.loadNewsList();
  },

  async mounted() {
    this.init();
    await this.whatPhone();
    setTimeout(() => {
      window.localStorage.removeItem("isreload");
    }, 5000);
    //暂时注释
    // await this.getWxCodeByLogin();
    getToken()
    this.getUnreadCount();
  },
  methods: {
    init() {
      // this.checkLoginUser();
      // this.getBannerList();
      // this.getNoticeList();
      // this.getWxSign();
    },
    checkLoginUser() {
      getLoginUserInfo().then(res => {
        if (res.code == 200) {
          console.log("登录校验成功");
        } else {
          console.log("退出重新登录");
          try {
            const storage = window.localStorage;
            storage.clear();
          } catch (err) {
            console.log("清理localStorage失败:" + err);
          }
          try {
            console.log("清理token");
            removeToken();
            removeWxUserinfoCookies();
          } catch (err) {
            console.log("清理token失败:" + err);
          }
        }
      });
    },
    // loginByOpenId
    loginByOpenId(openId, nickname, avatar, unionid) {
      loginByOpenId({
        openId,
        nickname,
        avatar,
        unionid
      }).then(response => {
        setToken(response.data.token);
        window.localStorage.setItem("openId", response.data.openId);
        this.$store.commit("updateTabbarItemShow", 0);
        this.$vux.toast.show("登录成功");
      });
    },
    getWxCodeByLogin() {
      //根据code登录
      if (this.$route.query.code || getWxUserinfoCookies()) {
        var user = "";
        try {
          user = JSON.parse(getWxUserinfoCookies());
        } catch (err) {
          console.log("获取微信信息失败:" + err);
        }
        if (user && user.openid) {
          console.log("USER:" + user);
          //用户信息已存
        } else {
          Vue.$vux.loading.show({text: "正在登录.."});
          setTimeout(function () {
            Vue.$vux.loading.hide();
          }, 5000);
          getWxUserInfo({
            code: this.$route.query.code
          }).then(res => {
            if (res.code == 200) {
              var resData = res.data;
              window.localStorage.setItem("openId", resData.openid);
              this.loginByOpenId(
                resData.openid,
                resData.nickname,
                resData.headimgurl,
                resData.unionid
              );
              // window.localStorage.setItem("wxUserinfo3",JSON.stringify(resData))
              setWxUserinfoCookies(JSON.stringify(resData));
            } else {
              alert("获取用户信息失败,请刷新重试");
            }
          });
        }
      } else {
        var isProd = true; //正式版true , 测试版 false
        if (isProd) {
          //正式
          window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3667ca0851ee1da2&redirect_uri=http%3a%2f%2fydkq.eaccessy.com%2f&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        } else {
          //TODO 开启console 调试模式
          // 测试
          window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3667ca0851ee1da2&redirect_uri=http%3a%2f%2fydkqyy.eaccessy.com%2f&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        }
      }
    },
    // 获取是ios 还是安卓
    whatPhone() {
      var u = navigator.userAgent,
        app = navigator.appVersion;
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //g
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if (isAndroid) {
        // alert("安卓机！");
      }
      if (isIOS) {
        // alert("苹果果机！");

        if (!window.localStorage.getItem("isreload")) {
          window.localStorage.setItem("isreload", 1);
          window.location.reload();
        }
      }
    },
    //打开活动规则页面
    showpopup() {
      this.popup = 1;
    },
    //关闭活动规则页面
    closepopup() {
      this.popup = 0;
    },
    handleErrorFn(e) {
      console.log("fail", e.detail);
    },

    handleLaunchFn(e) {
      console.log("success");
    },
    getWxSign() {
      getWxSign({
        url: window.location.href
      }).then(res => {
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印
          appId: res.data.appId, // 必填，公众号的唯一标识
          timestamp: res.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
          signature: res.data.signature, // 必填，签名
          jsApiList: ["openTagList", "onMenuShareTimeline", "scanQRCode"], // 必填，需要使用的JS接口列表
          openTagList: ["wx-open-launch-weapp"] // 可选，需要使用的开放标签列表，例如['wx-open-launch-app']
        });
        wx.ready(function () {
          console.log("ready");
          // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中
        });
        wx.error(function (res) {
          console.log("error:" + res);
          // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名
        });
        var btn = document.getElementById("launch-btn");
        btn.addEventListener("launch", function (e) {
          console.log("success");
        });
        btn.addEventListener("error", function (e) {
          console.log("fail", e.detail);
        });

        var btn1 = document.getElementById("launch-btn1");
        btn1.addEventListener("launch", function (e) {
          console.log("success");
        });
        btn1.addEventListener("error", function (e) {
          console.log("fail", e.detail);
        });
      });
    },
    getNoticeList() {
      getNoticeList().then(res => {
        if (res.code == 200) {
          this.noticeList = res.data;
        }
      });
    },
    scanFun() {
      const that = this;
      wx.scanQRCode({
        // 微信扫一扫接口
        desc: "scanQRCode desc",
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          var url = res.resultStr;
          var arr = url.match(/deptId(\S*)/);
          const deptQrCode = arr[1]; // 当needResult 为 1 时，扫码返回的结果
          // that.val=getCode
          //   window.location.href =location.href+`sign_in_index?idNo=${idNo}&deptQrCode=${deptQrCode}`
          if (deptQrCode) {
            that.$router.push({
              path: "/sign_in_select",
              query: {
                deptId: deptQrCode
              }
            });
          }
        },
        fail: function (res) {
          // alert("调取失败");
        }
      });
    },
    isLoginAndIsband() {
      const that = this;
      if (!getToken()) {
        var user2 = JSON.parse(getWxUserinfoCookies());
        that.$vux.confirm.show({
          // 组件除show外的属性
          content: "未登录,请先登录账号",
          onCancel() {
          },
          onConfirm() {
            that.loginByOpenId(
              user2.openid,
              user2.nickname,
              user2.headimgurl,
              user2.unionid
            );
          }
        });
        return false;
      } else {
        if (window.localStorage.getItem("isband") == "false") {
          that.$vux.confirm.show({
            // 组件除show外的属性
            content: "请添加就诊人",
            onCancel() {
            },
            onConfirm() {
              that.$router.push({path: "/my_patient"});
            }
          });
          return false;
        } else {
          return true;
        }
      }
    },
    toLink(item) {
      if (item.url) {
        window.location.href = item.url;
      }
    },
    onIndexChange(index) {
    },

    checkUser(link) {
      this.$api.family.list().then(res => {
        if (res.code == 200) {
          if (res.data == null) {
            // window.location.href = h5BaseUrl + 'registration'
            this.$router.push("/registration");
          } else {
            // window.location.href = h5BaseUrl + link.replace('/', '')
            this.$router.push(link);
          }
        }
      });
    },
    // 新增方法
    goActivity() {
      this.$router.push('/activity');
    },
    goMutual() {
      this.$router.push('/mutual');
    },
    async loadNewsList() {
      try {
        const res = await getNewsList({
          pageNum: '1',
          pageSize: '5'
        });
        
        if (res.code === 200 && res.data) {
          this.newsList = res.data.records || [];
        }
      } catch (error) {
        console.error('获取新闻列表失败:', error);
      }
    },
    formatNewsDate(date) {
      if (!date) return '';
      const dt = new Date(date);
      const year = dt.getFullYear();
      const month = String(dt.getMonth() + 1).padStart(2, '0');
      const day = String(dt.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleNewsClick(item) {
      if (item.source) {
        window.open(item.source, '_blank');
      }
    },
    async getUnreadCount() {
      try {
        const res = await getUnreadMessageCount({});
        if (res.code === 200) {
          this.unreadCount = res.data || 0;
        }
      } catch (error) {
        console.error('获取未读消息数失败:', error);
      }
    },
    getNewsIcon(type) {
      const iconMap = {
        '0': require('@/assets/img/new3.png'),  // 官方快讯图标
        '1': require('@/assets/img/new1.png'),  // 头条消息图标
        '2': require('@/assets/img/new2.png')        // 热点新闻图标
      };
      return iconMap[type] || iconMap['0'];
    },
    getNewsTypeText(type) {
      const typeMap = {
        '0': '官方快讯',
        '1': '头条消息',
        '2': '热点新闻'
      };
      return typeMap[type] || '官方快讯';
    },
    formatDate(date) {
      if (!date) return '';
      const dt = new Date(date);
      const year = dt.getFullYear();
      const month = String(dt.getMonth() + 1).padStart(2, '0');
      const day = String(dt.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style lang="less" scoped>
.home {
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background: #fff;
  
  span {
    font-size: 18px;
    font-weight: bold;
  }

  .header-right {
    display: flex;
    gap: 15px;
    
    img {
      width: 24px;
      height: 24px;
    }
  }
}

.school-header {
  position: relative;
  height: 120px;
  background: #1e4b9c;
  overflow: hidden;

  .logo-container {
    position: relative;
    z-index: 2;
    padding: 15px;
    display: flex;
    align-items: center;
    gap: 10px;

    .school-logo {
      width: 50px;
      height: 50px;
    }

    .school-name {
      color: #fff;
      font-size: 14px;
    }
  }

  .school-bg {
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
    opacity: 0.3;
  }
}

.swiper_box {
  height: 180px;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.quick_entry {
  display: flex;
  justify-content: space-around;
  padding: 20px 15px;
  background: #fff;
  margin: 10px 0;

  .entry_item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;

    img {
      width: 45px;
      height: 45px;
    }

    span {
      font-size: 14px;
      color: #333;
    }
  }
}

.news_section {
  background: #fff;
  padding: 15px;

  .news_header {
    .news_title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 15px;

      .title_bar {
        width: 3px;
        height: 16px;
        background: #1e4b9c;
      }

      span {
        font-size: 16px;
        font-weight: bold;
      }
    }
  }

  .news-list {
    .news-item {
      display: flex;
      align-items: center;
      padding: 15px;
      cursor: pointer;
      transition: all 0.3s ease;
      border-bottom: 1px solid #f0f0f0;

      &:hover {
        background-color: #f5f7fa;
      }

      .news-icon {
        margin-right: 15px;
        
        .type-icon {
          width: 24px;
          height: 24px;
          object-fit: contain;
        }
      }

      .news-content {
        flex: 1;
        overflow: hidden;

        .news-title {
          font-size: 14px;
          color: #303133;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .news-info {
          display: flex;
          align-items: center;
          font-size: 12px;
          color: #909399;

          .news-type {
            margin-right: 15px;
            padding: 2px 6px;
            background: #f0f2f5;
            border-radius: 4px;
          }

          .news-time {
            color: #c0c4cc;
          }
        }
      }
    }
  }
}

.bottom_nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 8px 0;
  background: #fff;
  border-top: 1px solid #eee;

  .nav_item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;

    img {
      width: 24px;
      height: 24px;
    }

    span {
      font-size: 12px;
      color: #666;
    }

    &:nth-child(3) img {
      width: 40px;
      height: 40px;
    }
  }
}

.message-icon {
  position: relative;
  display: inline-block;

  .message-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background: #f56c6c;
    color: #fff;
    border-radius: 10px;
    padding: 0 6px;
    font-size: 12px;
    line-height: 16px;
    min-width: 16px;
    text-align: center;
  }
}
</style>
<style>
.weui-dialog__btn_primary {
  color: #4790ff;
}

.home .vux-tab .vux-tab-item.vux-tab-selected {
  font-weight: bold;
  font-size: 1.125rem !important;
}

.home .vux-tab {
  /* background-color: #f0f5fb; */
}

.home .vux-tab .vux-tab-item {
  background-size: 100% 0rem;
}

.mask_confirm {
  width: 90%;
  background-color: #fff;
  height: 70%;
  margin: 0 auto;
  border-radius: 0.31rem;
  position: fixed;
  left: 5%;
  top: 10%;
  /* position: relative; */
}

.mask_confirm .tit {
  height: 2.81rem;
  line-height: 2.81rem;
  text-align: center;
  border-bottom: 0.06rem solid #e7ecf5;
  font-size: 1.13rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #448eff;
}

.mask_confirm .content {
  padding: 0rem 1rem;
  margin: 1.25rem 0;
  height: 66%;
  overflow-y: auto;
  line-height: 1.5rem;
}

.mask_confirm .btn {
  position: absolute;
  bottom: 0.94rem;
  left: calc((100% - 10.13rem) / 2);
  width: 10.13rem;
  height: 2.75rem;
  text-align: center;
  line-height: 2.75rem;
  background: linear-gradient(90deg, #448eff 0%, #66a3ff 100%);
  border-radius: 0.19rem;
  font-size: 1.13rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: #ffffff;
}
</style>
